package com.explore.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.explore.demo.VO.RecruitmentListVO;
import com.explore.demo.cache.RedisCache;
import com.explore.demo.common.ResultCode;
import com.explore.demo.common.ServerResponse;
import com.explore.demo.config.JwtConfig;
import com.explore.demo.mapper.HumanSourceMapper;
import com.explore.demo.mapper.RecruitmentMapper;
import com.explore.demo.pojo.Company;
import com.explore.demo.mapper.CompanyMapper;
import com.explore.demo.pojo.HumanSource;
import com.explore.demo.pojo.Recruitment;
import com.explore.demo.service.CompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.explore.demo.utils.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gaolainan
 * @since 2021-04-14
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService
{

    /**
     * 打印日志文件
     */
    private final Logger logger = LoggerFactory.getLogger(CompanyServiceImpl.class);

    @Resource
    private RecruitmentMapper recruitmentMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private FileUtils fileUtils;

    @Resource
    private RedisCache redisCache;

    @Resource
    private HumanSourceMapper humanSourceMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public ServerResponse addCompany(@NotNull String companyName,@NotNull String companyDesc, MultipartFile file, HttpServletRequest request)
    {
        Company company = new Company();
        synchronized (this){
            String token =  request.getHeader(jwtConfig.getHeader());
            String phone = jwtConfig.getUsernameFromToken(token);
            HumanSource humanSource = humanSourceMapper.selectOne(new QueryWrapper<HumanSource>().eq("phone", phone));
            String path = fileUtils.saveFile(file);
            company.setCompanyLogo(path)
                   .setCompanyName(companyName)
                   .setCompanyDesc(companyDesc);
            int insert = companyMapper.insert(company);
            if (insert == 0){
                return ServerResponse.createBySuccessMessage("fail", 2000, null);
            }
            Company tmp = companyMapper.getNewCompany();
            humanSource.setDepartmentId(tmp.getId());
            int update = humanSourceMapper.updateById(humanSource);
            if (update == 0){
                return ServerResponse.createBySuccessMessage("fail", 2000, null);
            }
        }
        return ServerResponse.createBySuccessMessage("success", 200, null);
    }

    @Override
    public ServerResponse deleteByCompanyName(String companyName)
    {
        if (companyName == null){
            return ServerResponse.createBySuccessMessage(ResultCode.COMPANY_NAME_IS_NULL.getDescription(),
                                                         ResultCode.COMPANY_NAME_IS_NULL.getCode(),
                                                         null);
        }
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper
                .eq("company_name",companyName);
        Company company = companyMapper.selectOne(wrapper);
        UpdateWrapper<Company> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("deleted",1);
        return companyMapper.update(company,updateWrapper) != 0?
               ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     null):
               ServerResponse.createBySuccessMessage(ResultCode.COMPANY_DELETE_FAIL.getDescription(),
                                                     ResultCode.COMPANY_DELETE_FAIL.getCode(),
                                                     null);
    }

    @Override
    public ServerResponse queryAll()
    {
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper
                .ge("id",1);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     companyMapper.selectList(wrapper));
    }

    @Override
    public ServerResponse queryByCompanyName(String companyName)
    {
        if (companyName == null){
            return ServerResponse.createBySuccessMessage(ResultCode.COMPANY_NAME_IS_NULL.getDescription(),
                                                         ResultCode.COMPANY_NAME_IS_NULL.getCode(),
                                                         null);
        }
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper
                .eq("company_name",companyName);
        Company company = companyMapper.selectOne(wrapper);
        List<String> categoryName = companyMapper.getCategoryName(company.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("company", company);
        map.put("category", categoryName);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     map);
    }

    @Override
    public ServerResponse updateCompany(Company company)
    {
        if (company == null){
            return ServerResponse.createBySuccessMessage(ResultCode.COMPANY_IS_NULL.getDescription(),
                                                         ResultCode.COMPANY_IS_NULL.getCode(),
                                                         null);
        }
        return companyMapper.updateById(company) != 0?
               ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     null):
               ServerResponse.createBySuccessMessage(ResultCode.UPDATE_FAIL.getDescription(),
                                                     ResultCode.UPDATE_FAIL.getCode(),
                                                     null);
    }

    @Override
    public ServerResponse uploadCompanyLogo(MultipartFile file)
    {
        String path = fileUtils.saveFile(file);
        logger.info("文件上传成功，上传的地址为：=============> "+path);
        return ServerResponse.createBySuccessMessage("上传成功", 200, path);
    }

    @Override
    public ServerResponse getAllRecruitmentByCompanyName(@NotNull String companyName)
    {
        List<Recruitment> recruitmentList = recruitmentMapper.getRecruitmentList(companyName);
        List<RecruitmentListVO> res = new ArrayList<>();
        for (Recruitment tmp : recruitmentList){
            RecruitmentListVO recruitmentListVO = new RecruitmentListVO();
            recruitmentListVO.setRecruitmentId(tmp.getId())
                             .setJob(tmp.getTitle())
                             .setExperience(tmp.getExperience())
                             .setNeedNum(tmp.getNeedNum())
                             .setWorkPlace(tmp.getWorkCity())
                             .setSalaryUp(tmp.getSalaryUp())
                             .setSalaryDown(tmp.getSalaryDown())
                             .setCreateTime(tmp.getCreateTime());
            res.add(recruitmentListVO);
        }
        return ServerResponse.createBySuccessMessage("success", 200, res);
    }
}
